// Updated Trackline.js to use single-click input editing for track numbers
import React, { useState } from 'react';

const Trackline = React.memo(({ rows, columns, cellSize, gap, lines, updateLine, deleteLine, deleteMode }) => {
  const calculateCenter = (row, col) => ({
    x: col * (cellSize + gap) + cellSize / 2,
    y: row * (cellSize + gap) + cellSize / 2,
  });

  const [draggingIndex, setDraggingIndex] = useState(null);
  const [labelOffsets, setLabelOffsets] = useState(
    lines.map(() => ({ dx: 0, dy: -6 }))
  );

  const [editingIndex, setEditingIndex] = useState(null);
  const [inputValue, setInputValue] = useState('');

  const handleDragStart = (index) => {
    setDraggingIndex(index);
  };

  const handleDrag = (e, index) => {
    if (draggingIndex === index) {
      const svg = e.target.ownerSVGElement.getBoundingClientRect();
      const dx = e.clientX - svg.left;
      const dy = e.clientY - svg.top;

      const { start, end } = lines[index];
      const { x: x1, y: y1 } = calculateCenter(start.row, start.col);
      const { x: x2, y: y2 } = calculateCenter(end.row, end.col);
      const midX = (x1 + x2) / 2;
      const midY = (y1 + y2) / 2;

      setLabelOffsets((prev) => {
        const updated = [...prev];
        updated[index] = { dx: dx - midX, dy: dy - midY };
        return updated;
      });
    }
  };

  const handleDragEnd = () => {
    setDraggingIndex(null);
  };

  const handleConfirmEdit = (index) => {
    updateLine(index, { ...lines[index], no: inputValue });
    setEditingIndex(null);
  };

  return (
    <g>
      {lines.map((line, index) => {
        const { start, end, no, occupied = false } = line;
        const { x: x1, y: y1 } = calculateCenter(start.row, start.col);
        const { x: x2, y: y2 } = calculateCenter(end.row, end.col);
        const midX = (x1 + x2) / 2;
        const midY = (y1 + y2) / 2;
        const offset = labelOffsets[index] || { dx: 0, dy: -6 };

        const handleClick = () => {
          if (deleteMode) {
            deleteLine(index);
          } else {
            setEditingIndex(index);
            setInputValue(no);
          }
        };

        return (
          <g key={index}>
            <line
              x1={x1}
              y1={y1}
              x2={x2}
              y2={y2}
              stroke={occupied ? 'red' : 'blue'}
              strokeWidth={6}
              strokeLinecap="round"
              onClick={handleClick}
            />

            {editingIndex === index ? (
              <foreignObject
                x={midX + offset.dx - 30}
                y={midY + offset.dy - 10}
                width={60}
                height={20}
              >
                <input
                  type="text"
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onBlur={() => handleConfirmEdit(index)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') handleConfirmEdit(index);
                  }}
                  style={{ width: '100%', fontSize: '10px' }}
                  autoFocus
                />
              </foreignObject>
            ) : (
              <text
                x={midX + offset.dx}
                y={midY + offset.dy}
                textAnchor="middle"
                fontSize="10"
                fill="#000"
                cursor="pointer"
                onClick={handleClick}
                onMouseDown={() => handleDragStart(index)}
                onMouseMove={(e) => handleDrag(e, index)}
                onMouseUp={handleDragEnd}
              >
                {no}
              </text>
            )}
          </g>
        );
      })}
    </g>
  );
});

export default Trackline;
